﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.ComponentModel;

namespace Vara.Utility
{
    public class List_To_DataTable
    {
        public static DataTable ConvertToDataTable<T>(IList<T> lst)
        {
            //create DataTable Structure
            DataTable DataTableToReturn = CreateTable<T>();
            Type entType = typeof(T);

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
            //get the list item and add into the list
            foreach (T item in lst)
            {
                DataRow row = DataTableToReturn.NewRow();
                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item);
                }
                DataTableToReturn.Rows.Add(row);
            }

            return DataTableToReturn;
        }

        public static DataTable CreateTable<T>()
        {
            //T –> ClassName
            Type entType = typeof(T);
            //set the datatable name as class name
            DataTable DataTableToReturn = new DataTable(entType.Name);
            //get the property list
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entType);
            foreach (PropertyDescriptor prop in properties)
            {
                //add property as column
                DataTableToReturn.Columns.Add(prop.Name, prop.PropertyType);
            }
            return DataTableToReturn;
        }
    }

}
